package com.study.samsung.Dao;

import com.study.samsung.Entity.Address;
import com.study.samsung.Utils.RowMapper;
import com.study.samsung.Utils.SQLHelper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class AddressDao {
    SQLHelper helper = new SQLHelper();

    public List<Address> selectAll(Integer uid){
        String sql="select * from address where uid = ? order by aid desc ";
        return helper.query(sql,new AddressRowMapper(),uid);
    }

    public Address selectOne(Integer aid){
        String sql = "select * from address where aid = ?";
        return helper.one(sql,new AddressRowMapper(),aid);
    }

    public Integer addAddress(Address address){
        String sql = "insert into address values(?,?,?,?,?,?,?,?,?)";
        return helper.update(sql,address.getAid(),
                address.getAddressname(),
                address.getSheng(),
                address.getShi(),
                address.getQu(),
                address.getAname(),
                address.getAphone(),
                address.getIsdefault(),
                address.getUid());
    }

    public Integer  changeIsdefault(Integer i){
        String sql = "update address set isdefault = 1 where aid = ?";
        String sql1 = "update address set isdefault = 0 where aid != ?";
        String b ="";
        int x = i;
        Integer c =helper.update(sql,i);
        if (c>0){
            return helper.update(sql1,x);
        }else {
            b = "更新失败请检查";
            System.out.println(b);
            return 0;
        }
    }

    public Integer delAddress(Integer aid){
        String sql = "Delete from address where aid=?";
        return helper.update(sql,aid);
    }

    public Integer bianjiAddress(Address address){
        String sql = "update address set addressname = ?,sheng = ?,shi = ?,qu = ?,aname = ?,aphone = ? where aid = ?";
        return helper.update(sql,address.getAddressname(),
                address.getSheng(),
                address.getShi(),
                address.getQu(),
                address.getAname(),
                address.getAphone(),
                address.getAid());
    }

    class AddressRowMapper implements RowMapper<Address> {

        @Override
        public Address map(ResultSet rs) throws SQLException {

            return new Address(
                    rs.getInt("aid"),
                    rs.getString("addressname"),
                    rs.getString("sheng"),
                    rs.getString("shi"),
                    rs.getString("qu"),
                    rs.getString("aname"),
                    rs.getString("aphone"),
                    rs.getInt("isdefault"),
                    rs.getInt("uid"));
        }
    }
}
